package com.hello.sky.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hello.sky.exception.SkyException;
import com.hello.sky.properties.BaiduGeoProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class BaiduGeoUtil {

    @Autowired
    private BaiduGeoProperties baiduGeoProperties;

    public Integer computeGeoDistance(String endLocation) {

        try {
            //获取商家经纬度
            Map originMap = getLngLat(baiduGeoProperties.getRestaurantAddr());
            String originLat = originMap.get("lat").toString();
            String originLng = originMap.get("lng").toString();

            //获取目标地点经纬度
            Map remoteMap = getLngLat(endLocation);
            String remoteLat = remoteMap.get("lat").toString();
            String remoteLng = remoteMap.get("lng").toString();

            //计算两个地点骑行距离返回
            return handleDistance(originLat, originLng, remoteLat, remoteLng);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw SkyException.cast("配送距离计算异常");
        }
    }

    private URI getAddrUri(String addr) throws URISyntaxException {
        StringBuilder sb = new StringBuilder(baiduGeoProperties.getGetAddrUrl());
        sb.append("address=");
        sb.append(addr);
        sb.append("&output=json&ak=");
        sb.append(baiduGeoProperties.getAk());
        sb.append("&callback=showLocation");
        URI uri = new URI(sb.toString());
        return uri;
    }

    private Map<String, String> getLngLat(String location) throws Exception {
        //构造http请求客户端
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet();

        //构造url
        URI uri = getAddrUri(location);
        get.setURI(uri);

        //发送请求
        CloseableHttpResponse restAddr = client.execute(get);

        //解析返回数据
        HttpEntity entity = restAddr.getEntity();
        String string = EntityUtils.toString(entity);
        String substring = string.substring(string.indexOf("(") + 1, string.lastIndexOf(")"));
        JSONObject parse = JSON.parseObject(substring);
        Map o = (Map) parse.get("result");
        JSONObject jsonObject = (JSONObject) o.get("location");
        BigDecimal Lng = (BigDecimal) jsonObject.get("lng");
        BigDecimal Lat = (BigDecimal) jsonObject.get("lat");
        String originLng = Lng.setScale(6, BigDecimal.ROUND_HALF_UP).toString();
        String originLat = Lat.setScale(6, BigDecimal.ROUND_HALF_UP).toString();

        //关闭资源
        client.close();

        //封装返回数据
        Map<String, String> map = new HashMap<>();
        map.put("lng", originLng);
        map.put("lat", originLat);
        return map;
    }

    private Integer handleDistance(String originLat, String originLng, String remoteLat, String remoteLng) throws Exception {
        //构造http请求客户端
        CloseableHttpClient client = HttpClients.createDefault();

        //构造url
        HttpGet get = new HttpGet();
        URI uri1 = new URI("https://api.map.baidu.com/direction/v2/riding?origin=" + originLat + "," + originLng + "&destination=" + remoteLat + "," + remoteLng + "&ak=Wn7xCtva43D0gs9AitKMXkRXgvjrF8J9");
        get.setURI(uri1);

        //发送请求
        CloseableHttpResponse response = client.execute(get);

        //解析返回值
        HttpEntity jjj = response.getEntity();
        String zzz = EntityUtils.toString(jjj);
        JSONObject ppp = (JSONObject) JSON.parse(zzz);
        JSONObject result = (JSONObject) ppp.get("result");
        List list = (List) result.get("routes");
        Map map = (Map) list.get(0);
        String m = map.get("distance").toString();
        System.out.println("两点骑行距离 " + m + " 米");
        log.info("两点距离：{}(米)", m);

        //关闭资源
        client.close();

        return Integer.valueOf(m);
    }

}
